<template>
  <div class="product-detail" v-loading="loading">
    <div class="product-container" v-if="product">
      <div class="product-image">
        <img :src="getImageUrl(product.imageUrl)" :alt="product.name">
      </div>
      <div class="product-info">
        <h1 class="product-name">{{ product.name }}</h1>
        <div class="product-category">分类：{{ getCategoryLabel(product.category) }}</div>
        <div class="product-price">¥{{ product.price }}</div>
        <div class="product-stock" :class="{ 'low-stock': product.stock < 10 }">
          库存：{{ product.stock }}
          <span v-if="product.stock < 10" class="stock-warning">库存紧张</span>
        </div>
        <div class="product-sales">销量：{{ product.sales }}</div>
        <div class="quantity-selector">
          <span>数量：</span>
          <el-input-number
            v-model="quantity"
            :min="1"
            :max="product.stock"
            size="small"
            :disabled="product.stock <= 0">
          </el-input-number>
        </div>
        <div class="product-actions">
          <el-button
            type="primary"
            :disabled="product.stock <= 0"
            @click="addToCart">
            {{ product.stock > 0 ? '加入购物车' : '暂时缺货' }}
          </el-button>
        </div>
        <div class="product-description">
          <h3>商品描述</h3>
          <p>{{ product.description || '暂无描述' }}</p>
        </div>
      </div>
    </div>
    <div v-else-if="!loading" class="not-found">
      <el-empty description="商品不存在或已下架"></el-empty>
    </div>
  </div>
</template>

<script>
import { getProductDetail } from '@/api/product'
import { mapActions } from 'vuex'

export default {
  name: 'ProductDetail',
  data() {
    return {
      loading: true,
      product: null,
      quantity: 1,
      categories: [
        { value: 'food', label: '宠物食品' },
        { value: 'toys', label: '玩具用品' },
        { value: 'health', label: '保健品' },
        { value: 'daily', label: '日用品' }
      ]
    }
  },
  created() {
    this.fetchProductDetail()
  },
  methods: {
    ...mapActions('cart', ['addProductToCart']),

    async fetchProductDetail() {
      try {
        this.loading = true
        const id = this.$route.params.id
        if (!id) {
          this.$message.error('商品ID不能为空')
          this.$router.push('/shop')
          return
        }

        const response = await getProductDetail(id)
        console.log('Product detail response:', response)
        
        if (response && response.code === 200 && response.data) {
          this.product = response.data
        } else {
          this.$message.error('商品不存在或已下架')
          this.$router.push('/shop')
        }
      } catch (error) {
        console.error('获取商品详情失败:', error)
        this.$message.error('获取商品详情失败')
        this.$router.push('/shop')
      } finally {
        this.loading = false
      }
    },

    getCategoryLabel(value) {
      const category = this.categories.find(item => item.value === value)
      return category ? category.label : '未分类'
    },

    async addToCart() {
      if (!this.product) {
        this.$message.error('商品信息不存在')
        return
      }

      if (this.quantity > this.product.stock) {
        this.$message.warning('购买数量不能超过库存数量')
        return
      }

      try {
        await this.addProductToCart({
          productId: this.product.id,
          quantity: this.quantity
        })
        this.$message.success('添加到购物车成功')
      } catch (error) {
        console.error('添加到购物车失败:', error)
        this.$message.error(error.message || '添加到购物车失败')
      }
    },

    getImageUrl(path) {
      if (!path) {
        return require('@/assets/default.jpg');
      }
      
      // 服务器地址
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址
      
      // 如果路径已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }
      
      // 确保路径以 / 开头
      if (!path.startsWith('/')) {
        path = '/' + path;
      }
      
      // 构建完整URL
      return serverUrl + path;
    }
  }
}
</script>

<style lang="scss" scoped>
.product-detail {
  padding: 20px;
  min-height: calc(100vh - 60px);

  .product-container {
    display: flex;
    gap: 40px;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    @media (max-width: 768px) {
      flex-direction: column;
    }

    .product-image {
      flex: 0 0 400px;
      height: 400px;
      overflow: hidden;
      border-radius: 4px;

      @media (max-width: 768px) {
        flex: none;
        height: 300px;
      }

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .product-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 15px;

      .product-name {
        margin: 0;
        font-size: 24px;
        color: #333;
      }

      .product-category {
        color: #666;
      }

      .product-price {
        font-size: 28px;
        color: #f56c6c;
        font-weight: bold;
      }

      .product-stock {
        font-size: 14px;
        color: #666;

        &.low-stock {
          color: #e6a23c;
        }

        .stock-warning {
          margin-left: 10px;
          color: #f56c6c;
        }
      }

      .product-sales {
        color: #666;
      }

      .quantity-selector {
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .product-actions {
        margin: 20px 0;
      }

      .product-description {
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #eee;

        h3 {
          margin: 0 0 10px;
          font-size: 16px;
          color: #333;
        }

        p {
          margin: 0;
          color: #666;
          line-height: 1.6;
        }
      }
    }
  }

  .not-found {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400px;
  }
}
</style> 